#include "user_global.h"
#include "modbus.h"
#include "user_device.h"

ushort Read_RO_word(ushort addr)
{
    bit check = 1;
    uchar i = 0;
    uchar size = sizeof(ro_long_addL);
    for(i = 0;i < sizeof(ro_long_addL) && addr <= ro_long_addL[size-1];++i)
    {
        if(addr == ro_long_addL[i])
        {
            addr += 1;
            check = 0;
            break;
        }
    }

    if(check)
    {
        size = sizeof(ro_long_addH);
        for(i = 0;i < sizeof(ro_long_addH) && addr <= ro_long_addH[size -1];++i)
        {
            if(addr == ro_long_addH[i])
            {
                addr -= 1;
                break;
            }
        }
    }

    if(addr >=rochar[0].start && addr <= rochar[RO_CHAR_COUNT-1].end)
    {
        for(i = 0; i < RO_CHAR_COUNT; ++i)
        {
            if(addr >= rochar[i].start && addr <= rochar[i].end)
                return from_little_endian_16(RO_WORD_FIRST[addr]);
        }
    }
    if(addr == 0)
        return ps_server_busy ? 0xFFFF : ro_word.server_status;
    return RO_WORD_FIRST[addr];
}

ushort Read_RW_word(ushort addr)
{
    bit check = 1;
    uchar i;
    for(i = 0; i < sizeof(rw_long_addL); ++i)
    {
        if(addr == rw_long_addL[i])
        {
            addr += 1;
            check = 0;
            break;
        }
    }

    if(check)
    {
        for(i = 0;i < sizeof(rw_long_addH);++i)
        {
            if(addr == rw_long_addH[i])
            {
                addr -= 1;
                break;
            }
        }
    }
    return RW_WORD_FIRST[addr];
}

void Write_word(ushort addr, ushort val)
{
    bit check = 1;
    uchar i;
    for(i = 0;i < sizeof(rw_long_addL);++i)
    {
        if(addr == rw_long_addL[i])
        {
            addr += 1;
            check = 0;
            break;
        }
    }

    if(check)
    {
        for(i = 0;i < sizeof(rw_long_addH);++i)
        {
            if(addr == rw_long_addH[i])
            {
                addr -= 1;
                break;
            }
        }
    }

    RW_WORD_FIRST[addr] = val;

    if (addr == 0)
    {
        pending_role = ACTION_PENDING_MODBUS_EVENT;
        pending_action = 1;
    }
}
